package cn.bytets.rpc.common.utils;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

public class NamedTheadFactory implements ThreadFactory {
    /**
     * 为了计算,在创建线程时区别线程名称
     */
    protected static final AtomicInteger POOL_SEQ = new AtomicInteger(1);

    protected final AtomicInteger mThreadNum = new AtomicInteger(1);

    protected final String mPrefix;

    protected final boolean mDaemon;

    protected final ThreadGroup mGroup;

    public NamedTheadFactory(){
        this("pool-"+POOL_SEQ.incrementAndGet(),false);
    }
    public NamedTheadFactory(String threadName){
        this(threadName,false);
    }
    public NamedTheadFactory(String threadName,boolean mDaemon){
        this.mPrefix = threadName+"-thread-";
        this.mDaemon = mDaemon;
        SecurityManager securityManager = System.getSecurityManager();
        this.mGroup = null==securityManager?Thread.currentThread().getThreadGroup():securityManager.getThreadGroup();
    }
    @Override
    public Thread newThread(Runnable r) {
        String name = mPrefix + mThreadNum.getAndIncrement();
        Thread thread = new Thread(this.mGroup,r,name,0);
        thread.setDaemon(mDaemon);
        return thread;
    }
    public ThreadGroup getmGroup(){
        return this.mGroup;
    }
}
